<?php

namespace plugins\upload\controller;


use app\common\controller\BasePlugin;
use League\Flysystem\FileNotFoundException;
use plugins\upload\model\AttachmentModel;
use think\facade\Filesystem;
use think\facade\Request;

class UploadPlugin extends BasePlugin
{


    protected static string $upload_driver = 'public';

    protected static string $upload_path = 'uploads';

    protected static array $upload_data = [];

    protected static string $error_message = '';

    public function initialize(): void
    {
        parent::initialize();
        self::$upload_data = [
            'code'    => 0,
            'message' => '上传失败',
            'data'    => []
        ];
        // 取插件配置
    }

    /**
     * 上传图片/文件
     *
     * @param string $upType       上传类型 image/file/avatar/base64
     * @param string $form_name    表单名
     * @param string $imageData    Base64数据
     * @param string $save_name    存储名称
     * @param bool   $isAttachment 是否存储附件
     *
     * @return array
     * @throws FileNotFoundException
     */
    public static function do_upload(string $upType = 'image', string $form_name = 'image', string $imageData = '', string $save_name = '', bool $isAttachment = true): array
    {
        $saveName = $save_name ?: md5(uniqid(microtime(true), true)) . '.png';
        $savePath = $form_name . '/';
        if ($upType == 'base64') {
            $result = Filesystem::disk(self::$upload_driver)->put($savePath . $saveName, self::base64ToImage($imageData));
            if ($result) {
                $metaData = Filesystem::disk(self::$upload_driver)->getMetadata($savePath . $saveName);
                $fileSize = $metaData['size'];
                $fileMime = 'image/png';
                $fileExt  = strrchr($saveName, '.');
                $fileType = 'image';
            } else {
                self::set_error('文件保存失败！');
                return self::$upload_data;
            }
        } else {
            $file = Request::file($form_name);
            if (empty($file)) {
                self::set_error('上传文件为空');
                return self::$upload_data;
            }
            $saveName = Filesystem::disk(self::$upload_driver)->putFile($savePath, $file);
            if (!$saveName) {
                self::set_error('文件保存失败！');
                return self::$upload_data;
            }
            $fileSize = $file->getSize();
            $fileMime = $file->getMime();
            $fileExt  = $file->getExtension();
            $fileType = $file->getType();
        }
        if ($saveName && $isAttachment) {
            self::save_attachment($saveName, $savePath, $fileSize, $fileType, $fileExt, $fileMime);
        }
        return self::$upload_data;
    }

    private static function base64ToImage(string $imageData): false|string
    {
        return base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageData));
    }

    private static function set_error(string $error_message = ''): void
    {
        self::$error_message = $error_message;
        self::$upload_data   = [
            'code'    => 0,
            'message' => $error_message,
            'data'    => []
        ];
    }

    /**
     * 写入附件数据
     *
     * @param string     $saveName
     * @param string     $savePath
     * @param int|string $size
     * @param string     $type
     * @param string     $ext
     * @param string     $mime
     *
     * @return void
     */
    private static function save_attachment(string $saveName, string $savePath, int|string $size = 0, string $type = '', string $ext = '', string $mime = ''): void
    {
        $attachment = [
            'file_name'       => $saveName,
            'file_path'       => $savePath,
            'file_size'       => $size,
            'file_type'       => $type,
            'file_md5'        => '',
            'file_sha1'       => '',
            'file_ext'        => $ext,
            'file_mime'       => $mime,
            'file_width'      => '',
            'file_height'     => '',
            'file_duration'   => '',
            'file_frame_rate' => '',
            'storage'         => self::$upload_driver
        ];
        AttachmentModel::create($attachment);
        self::set_data($savePath.$saveName);
    }

    private static function set_data(string $save_name = ''): void
    {
        self::$upload_data = [
            'code'    => 1,
            'message' => '上传成功',
            'data'    => [
                'url'       => '/uploads/' . $save_name,
                'save_name' => $save_name
            ]
        ];
    }

    public static function get_error(): string
    {
        return self::$error_message;
    }

    public static function get_upload_data(): array
    {
        return self::$upload_data;
    }

    public static function checkImage(string $image, string $type = 'image')
    {

    }
}